<template>
  <div class="index">
    <!-- 轮播图 -->
    <swiper class="swiper" indicator-dots="true" autoplay="true" interval="5000" duration="1000">
      <block v-for="(item, index) in bannerList" :index="index" :key="item">
        <swiper-item>
          <navigator :url="item.url">
            <div style="position:absolute;width:100%;height:100%;z-index:-1;">
              <image style="width:100%;height:100%;" :src="item.imgUrl" class="slide-image" mode="scaleToFill" />
            </div>
          </navigator>
        </swiper-item>
      </block>
    </swiper>
    <!-- 轮播图 -->
    <!-- 宫格 -->
    <van-grid column-num="4" :border="false">
      <van-grid-item use-slot v-for="(item, index) in classifyList" :title="item.name" :key="index" :url="item.url">
        <image style="border-radius: 22px;width: 36px; height: 36px;" :src="item.icon" @click="toPage(item)" />
        <div class="classlyIcon">{{item.name}}</div>
      </van-grid-item>
    </van-grid>
    <!-- 宫格 -->
    <!-- 单元格 -->
    <van-cell-group>
      <van-cell title="热销商品" value="更多" is-link link-type="navigateTo" @click="toHotPage()" />
    </van-cell-group>
    <!-- 单元格 -->
    <!-- 宫格 -->
    <van-grid column-num="3" :border="false">
      <van-grid-item use-slot v-for="(item, index) in hotGoodsList" :title="item.name" :key="index">
        <image style="width: 100%; height: 100px;" :src="item.icon" @click="viewGoodsDetail(item.id)" />
        <div style="width:100%">
          <div class="goodName">{{item.name}}</div>
        </div>
        <div style="width:100%">
          <div style="display:inline;float:left;font-size:60%;color:#FF0000">￥{{item.price}}</div>
          <div style="display:inline;float:right;font-size:60%;" class="classlyIcon">库存:{{item.stock}}</div>
        </div>
      </van-grid-item>
    </van-grid>
    <!-- 宫格 -->
    <van-tabs :active="activate" @change="changeTab">
      <van-tab v-for="nav in navList" :title="nav.name" v-bind:key="nav.id"></van-tab>
    </van-tabs>

    <van-card v-for="(goods, index) in goodsList" :key="index" :num="goods.num" :price="goods.price" :desc="goods.descript" :title="goods.name" :thumb="goods.imgUrl" @click="viewGoodsDetail(goods.id)" />
  </div>
</template>

<script>
import card from "@/components/card";
import utils from "@/utils/index.js";
// import { Toast } from "vant";
export default {
  config: {
    navigationBarTitleText: "邻家小铺"
  },
  data() {
    return {
      bannerList: [],
      classifyList: [],
      hotGoodsList: [],
      navList: [],
      goodsList: [],
      tagsAndGoodsDict: {},
      activeNav: 0,
      activate: 0,
      listQuery: {
        page: 1,
        limit: 20,
        tagId: 0
      }
    };
  },
  components: {
    card
  },
  methods: {
    changeTab(event) {
      const index = event.mp.detail.index;
      this.goodsList = this.tagsAndGoodsDict[this.navList[index].id];
    },
    viewGoodsDetail(id) {
      const url = "../goods/index?id=" + id;
      wx.navigateTo({ url });
    },
    toClassifyPage(item) {
      const url = "../categoryList/index?id=" + item.parentId;
      wx.navigateTo({ url });
    },
    toDetailListPage(item) {
      const url = "../categoryList/list?id=" + item.id;
      wx.navigateTo({ url });
    },
    toPage(item) {
      if (item.name == "全部分类") {
        this.toClassifyPage(item);
      } else {
        this.toDetailListPage(item);
      }
    },
    toHotPage() {
      const url = "../index/hotGoods";
      wx.navigateTo({ url });
    },
    getCategoryList() {
      this.$API
        .get("/category/list")
        .then(res => {
          this.navList = res.data;
          // this.listQuery.tagId = res.data[0].id;
        })
        .catch(e => { });
    },

    getGoodsList() {
      this.$API
        .get("goods/queryGoods?page=" +
          this.listQuery.page +
          "&limit=" +
          this.listQuery.limit +
          "&idCategory=" +
          this.listQuery.idCategory,
          this.listQuery
        )
        .then(res => {
          let goodsList = res.data.records;
          for (let i = 0; i < goodsList.length; i++) {
            goodsList[i].price = utils.formatPrice(goodsList[i].price);
            goodsList[i].imgUrl = utils.fileMgrUrl + goodsList[i].pic;
          }
          this.goodsList = goodsList;
        })
        .catch(e => { });
    },
    getHotGoodsList() {
      // 获取热门商品
      this.$API.get("goods/searchHot").then(res => {
        let tmpHotGoodsList = res.data;
        let length = 12;
        if (tmpHotGoodsList.length < 9){
          length = tmpHotGoodsList.length
        }

        for (let i = 0; i < length; i++) {
          const e = tmpHotGoodsList[i];
          let t = {
            id: e.id,
            name: e.name,
            stock: e.stock,
            gallery: e.gallery,
            idCategory: e.idCategory,
            descript: e.descript,
            detail: e.detail,
            price: (e.price / 100).toFixed(2),
            icon: utils.fileMgrUrl + e.pic
          };
          this.hotGoodsList.push(t);
        }
      });
    },
    getBannerList() {
      // 获取轮播图图片
      this.$API.get("/banner/list").then(res => {
        let tmpBannerList = res.data;
        tmpBannerList = this.processBanners(tmpBannerList);

        for (let i = 0; i < tmpBannerList.length; i++) {
          this.bannerList.push(tmpBannerList[i]);
        }
      });
    },
    getHotCategory() {
      // 获取热门分类
      this.$API.get("/category/getHotCategory").then(res => {
        let tmpClassifyList = res.data;

        for (let i = 0; i < tmpClassifyList.length; i++) {
          const e = tmpClassifyList[i];
          let t = {
            id: e.id,
            name: e.name,
            icon: utils.fileMgrUrl + e.icon,
            parentId: e.fistId
          };
          this.classifyList.push(t);
        }
        let all = {
          id: 0,
          name: "全部分类",
          icon: utils.fileMgrUrl + "7cc07f0b-c36e-4781-affe-cd068cc319d6.png"
        };
        this.classifyList.push(all);
      });
    },
    processBanners(banners) {
      for (let i = 0; i < banners.length; i++) {
        let url = "";
        let page = banners[i].page;
        let param = banners[i].param;

        if (!utils.startWith(page, "http")) {
          url = "../" + page + "/index";
        }
        if (param !== "") {
          const paramJson = JSON.parse(param);
          let i = 0;
          for (const key in paramJson) {
            if (i === 0) {
              url += "?" + key + "=" + paramJson[key];
            } else {
              url += "&" + key + "=" + paramJson[key];
            }
            i++;
          }
        }

        banners[i].url = url;
        banners[i].imgUrl = utils.fileMgrUrl + banners[i].idFile;
      }
      return banners;
    },
    getTagsAndGoodList() {
      this.$API
        .get("/label/getRecommendLabel")
        .then(res => {

          this.navList = res.data;
          if (this.navList.length < 1) {
            return;
          }
          for (let i = 0; i < this.navList.length; i++) {
            const e = this.navList[i];
            this.tagsAndGoodsDict[e.id] = [];
            for (let j = 0; j < e.labelGoodsList.length; j++) {
              const e2 = e.labelGoodsList[j];
              let g1 = {
                price: utils.formatPrice(e2.goods.price),
                imgUrl: utils.fileMgrUrl + e2.goods.pic,
                descript: e2.goods.descript,
                name: e2.goods.name,
                num: e2.goods.num,
                id: e2.goods.id
              };
              this.tagsAndGoodsDict[e.id].push(g1);
            }
            if (i == 0) {
              this.goodsList = this.tagsAndGoodsDict[e.id];
            }
          }
          // for (let i = 0; i < goodsList.length; i++) {
          //   goodsList[i].price = utils.formatPrice(goodsList[i].price);
          //   goodsList[i].imgUrl = utils.fileMgrUrl + goodsList[i].pic;
          // }
          // this.goodsList = goodsList;
        })
        .catch(e => { });
    }
  },

  created() { },
  onShareAppMessage() {
    return {
      title: '兰大管院校友会商城'
    }
  },
  onShareTimeline() {
    return {
      title: '兰大管院校友会商城'
    }
  },
  onLoad() {
    let that = this;
    wx.setNavigationBarTitle({
      title: "首页"
    })
    that.bannerList = [];
    that.classifyList = [];
    that.hotGoodsList = [];
    that.navList = [];
    that.goodsList = [];
    // 轮播图
    that.getBannerList();
    // 热门分类
    that.getHotCategory();
    // 获取热门商品
    that.getHotGoodsList();
    // 获取所有首页推荐标签
    that.getTagsAndGoodList();

    // this.getCategoryList();
    // this.getGoodsList();
  }
};
</script>

<style >
swiper {
  height: 220px;
}
swiper-item > navigator > image {
  width: 100%;
}

.goodName {
  float: left;
  font-size: 60%;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
}

.classlyIcon {
  font-size: 60%;
  line-height: var(--card-desc-line-height, 15px);
  color: var(--card-desc-color, #7d7e80);
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
}
</style>
